package com.sphd.education.utils;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.format.Time;
import android.util.Log;

import com.sphd.education.info.UpdataInfo;
import com.sphd.education.modle.EducationUrl;

import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by admin on 2015/10/22.
 */
public class CheckUpdate {
    private String localVersion;//获取本地版本号
    private final int UPDATA_NONEED = 0;//不需要更新
    private final int UPDATA_CLIENT = 1;//通知用户更新
    private final int GET_UNDATAINFO_ERROR = 2;//获取信息出错
    private final int SDCARD_NOMOUNTED = 3;
    private final int DOWN_ERROR = 4;//下载出错
    private UpdataInfo info;
    Context context;
    String time;
    AlertDialog.Builder builder;
    public CheckUpdate(Context context) {
        this.context=context;
        builder = new AlertDialog.Builder(context);
    }

    /***
     * 获取包名
     * */
    private String getVersionName() throws Exception {
        //getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageManager packageManager = context.getPackageManager();

        PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(),
                0);
//        Log.e("package", "版本名"+packInfo.versionName);
        return packInfo.versionName;
    }

    public void checkUp() {
        try {
            localVersion = getVersionName();

            CheckVersionTask cv = new CheckVersionTask();
            new Thread(cv).start();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public class CheckVersionTask implements Runnable {
        InputStream is;
        public void run() {
            try {
                String path =EducationUrl.HttpTitle+ EducationUrl.UPDATA;
//                Log.e("aaa", "111");
                URL url = new URL(path);
//                Log.e("aaa","222");
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
//                Log.e("aaa","333");
                conn.setConnectTimeout(5000);
//                Log.e("aaa","444");
                conn.setRequestMethod("GET");
//                Log.e("aaa","555");
                int responseCode = conn.getResponseCode();
//                Log.e("responseCode",responseCode+"");
                if (responseCode == 200) {
                    // 从服务器获得一个输入流
                    is = conn.getInputStream();
                }
//                Log.e("is",is+"");
                info = UpdataInfoParser.getUpdataInfo(is);
//                Log.e("info",info+"");
                if (info.getVersion().equals(localVersion)) {
//                    Log.i(TAG, "版本号相同" + info.getVersion());
                    Message msg = new Message();
                    msg.what = UPDATA_NONEED;
                    handlerupdate.sendMessage(msg);
                    // LoginMain();
                } else {
//                    Log.i(TAG, "版本号不相同 "+info.getVersion());
                    Message msg = new Message();
                    msg.what = UPDATA_CLIENT;
                    handlerupdate.sendMessage(msg);
                }
            } catch (Exception e) {
                Message msg = new Message();
                msg.what = GET_UNDATAINFO_ERROR;
                handlerupdate.sendMessage(msg);
                e.printStackTrace();
            }
        }
    }
    Handler handlerupdate = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case UPDATA_NONEED:
                    builder.setTitle("提示");
                    builder.setMessage("不需要更新");
                    builder.setPositiveButton("好的", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.create().show();
                    break;
                case UPDATA_CLIENT:
                    //对话框通知用户升级程序
                    showUpdataDialog();
                    break;
                case GET_UNDATAINFO_ERROR:
                    //服务器超时
                    builder.setTitle("提示");
                    builder.setMessage("获取服务器更新信息失败");
                    builder.setPositiveButton("好的", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.create().show();
                    break;
                case DOWN_ERROR:
                    //下载apk失败
                    builder.setTitle("提示");
                    builder.setMessage("下载新版本失败");
                    builder.setPositiveButton("好的", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.create().show();
                    break;
            }
        }
    };
    /*
	 *
	 * 弹出对话框通知用户更新程序
	 *
	 * 弹出对话框的步骤：
	 *  1.创建alertDialog的builder.
	 *  2.要给builder设置属性, 对话框的内容,样式,按钮
	 *  3.通过builder 创建一个对话框
	 *  4.对话框show()出来
	 */
    protected void showUpdataDialog() {
        Time t=new Time(); // or Time t=new Time("GMT+8"); 加上Time Zone资料。
        t.setToNow(); // 取得系统时间。
        time=t.year+"年"+(t.month+1)+"月"+t.monthDay+"日";
        builder.setTitle("提示");
        builder.setMessage("检测到有版本需要升级吗？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                downLoadApk();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();

    }
    /*
     * 从服务器中下载APK
     */
    protected void downLoadApk() {
        final ProgressDialog pd;    //进度条对话框
        pd = new  ProgressDialog(context);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载更新");
        pd.show();
        new Thread(){
            @Override
            public void run() {
                try {
                    File file = DownLoadManager.getFileFromServer(info.getUrl(), pd);
                    sleep(3000);
                    installApk(file);
                    pd.dismiss(); //结束掉进度条对话框
                } catch (Exception e) {
                    Message msg = new Message();
                    msg.what = DOWN_ERROR;
                    handlerupdate.sendMessage(msg);
                    e.printStackTrace();
                }
            }}.start();
    }

    //安装apk
    protected void installApk(File file) {
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        //执行的数据类型
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }
}
